<template>
  <div class="app-container">
    <!-- 搜索 -->
    <div class="filter-container">
      <div v-if="checkPermission(['users@POST'])" class="filter-button">
        <el-button
          v-permission="['users@POST']"
          class="el-icon-edit"
          type="primary"
          @click="add"
        >新增
        </el-button>
      </div>
      <div class="filter-form">
        <el-form :model="filter" :inline="true" size="medium">
          <el-form-item label="">
            <el-input v-model="filter.username" placeholder="请输入用户名" />
          </el-form-item>
          <el-form-item label="">
            <el-input v-model="filter.id_no" placeholder="请输入工号" />
          </el-form-item>
          <el-form-item label="">
            <el-input v-model="filter.mobile" placeholder="请输入联系电话" />
          </el-form-item>
        </el-form>
        <div>
          <el-button v-permission="['users@GET']" @click="search">
            搜索
          </el-button>
          <el-button
            v-permission="['users@GET']"
            @click="resetForm"
          >重置
          </el-button>
        </div>
      </div>
    </div>
    <div v-loading="listLoading" class="content-container">
      <el-table
        :cell-style="{ textAlign: 'center' }"
        :data="list"
        border
        style="width: 100%"
        row-key="id"
        :header-cell-class-name="headerStyle"
        size="mini"
      >
        <el-table-column prop="name" label="姓名" />
        <el-table-column prop="id_no" label="工号" />
        <el-table-column prop="username" label="用户名" />
        <el-table-column prop="mobile" label="联系方式" />
        <el-table-column prop="roles" label="角色">
          <template slot-scope="{ row }">
            {{ row.roles_node.name }}
          </template>
        </el-table-column>
        <el-table-column prop="status_name" label="启用状态">
          <template slot-scope="{ row }">
            <span :class="`title-tag user-tag-${row.status} title-user-${row.status}`">{{ row.status_name }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="last_login_time" label="最后登录时间">
          <template slot-scope="{ row }">
            <span>{{ row.last_login_time }}</span>
          </template>
        </el-table-column>
        <el-table-column v-if="checkPermission(['users@PUT','users@DELETE'])" label="操作" width="250px" fixed="right">
          <template slot-scope="{ row }">
            <el-button
              v-permission="['users@PUT']"
              type="text"
              size="mini"
              @click="edit(row)"
            >
              编辑
            </el-button>
            <el-button
              v-if="row.status == '1' && row.id !==1"
              v-permission="['users@PUT']"
              type="text"
              size="mini"
              @click="status(row)"
            >
              停用
            </el-button>
            <el-button
              v-if="row.status == '0'"
              v-permission="['users@PUT']"
              type="text"
              size="mini"
              @click="status(row)"
            >
              启用
            </el-button>

            <el-button
              v-if="row.id !==1"
              v-permission="['users@DELETE']"
              type="text"
              class="button-red"
              size="mini"
              @click="del(row)"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <el-dialog
      :title="title"
      :visible.sync="dialogVisible"
    >
      <el-form
        ref="editForm"
        :rules="userRules"
        :model="editForm"
        label-width="100px"
      >
        <el-form-item label="姓名: " prop="name">
          <el-input v-model="editForm.name" placeholder="请输入姓名" />
        </el-form-item>
        <el-form-item label="工号: " prop="id_no">
          <el-input v-model="editForm.id_no" placeholder="请输入登录工号" />
        </el-form-item>
        <el-form-item label="用户名: " prop="username">
          <el-input v-model="editForm.username" placeholder="请输入用户名" />
        </el-form-item>
        <el-form-item label="密码: " prop="password" :rules="editForm.id? rules.password : rules.uppassword">
          <el-input
            v-model="editForm.password"
            :placeholder="text"
          />
        </el-form-item>
        <el-form-item label="联系方式: " prop="mobile">
          <el-input v-model="editForm.mobile" placeholder="请输入联系方式" />
        </el-form-item>
        <el-form-item label="赋予角色" prop="roles">
          <el-select
            v-model="editForm.roles"
            filterable
            default-first-option
            placeholder="请选择角色"
            value-key="name"
            style="width:100%"
          >
            <el-option
              v-for="item in allRole"
              :key="item.id"
              :label="item.name"
              :value="item"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="submit">
          确定
        </el-button>
      </div>
    </el-dialog>
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="filter.page"
      :limit.sync="filter.limit"
      @pagination="getList"
    />
  </div>
</template>
<script>
import layoutMinix from '@/layout/components/mixins/layout'
import Pagination from '@/components/Pagination'
import { getUserList, addUser, updateUser, delUser, statusUser } from '@/api/auth'
import { allRole } from '@/api/role'
import checkPermission from '@/utils/permission' // 权限判断函数

const defaultUser = {
  id: undefined,
  username: '',
  password: '',
  name: '',
  id_no: '',
  mobile: '',
  roles: []
}
export default {
  name: 'UserPermission',
  components: { Pagination },
  mixins: [layoutMinix],
  data() {
    const validatePassword = (rule, value, callback) => {
      if (!value && !this.editForm.id) {
        callback(new Error('请输入密码'))
        return
      }
      if (value && value.length < 6) {
        callback(new Error('密码长度不能低于6位'))
      } else {
        callback()
      }
    }
    return {
      text: '',
      list: [],
      total: 0,
      filter: {
        page: 1,
        limit: 20,
        username: '',
        id_no: '',
        mobile: ''
      },
      listLoading: false,
      editForm: Object.assign({}, defaultUser),
      rules: {
        password: [
          { required: false, trigger: 'blur', validator: validatePassword }
        ],
        uppassword: [
          { required: true, trigger: 'blur', validator: validatePassword }
        ]
      },
      userRules: {
        name: [
          { required: true, trigger: 'blur', message: '请输入姓名' }
        ],
        username: [
          { required: true, trigger: 'blur', message: '请输入用户名' }
        ],
        id_no: [
          { required: true, trigger: 'blur', message: '请输入登录工号' }
        ],
        mobile: [
          { required: true, trigger: 'blur', message: '请输入联系方式' }
        ],
        roles: [
          { required: true, trigger: 'blur', message: '请选择角色' }
        ]
      },
      dialogVisible: false,
      title: '',
      allRole: [
        {
          id: 0,
          name: '无权限'
        }
      ]
    }
  },
  mounted() {
    this.getList()
  },
  methods: {
    checkPermission,
    headerStyle({ row, rowIndex }) {
      return 'table-th'
    },
    getList() {
      this.listLoading = true
      getUserList(this.filter).then((response) => {
        const { list, total } = response.data
        this.list = list
        this.total = total
        this.listLoading = false
      })
    },
    getAllRole() {
      allRole().then((response) => {
        const { data } = response
        this.allRole = data
      })
    },
    add() {
      this.editForm = Object.assign({}, defaultUser)
      this.getAllRole()
      this.title = '添加用户'
      this.text = ''
      this.dialogVisible = true
      this.$nextTick(() => {
        this.$refs.editForm.clearValidate()
      })
    },
    submit() {
      this.$refs.editForm.validate((valid) => {
        if (valid) {
          if (this.editForm.id !== undefined) {
            updateUser(this.editForm).then(() => {
              this.$message.success('修改成功')
              this.getList()
              this.dialogVisible = false
            })
          } else {
            addUser(this.editForm).then(() => {
              this.$message.success('添加成功')
              this.getList()
              this.dialogVisible = false
            })
          }
        } else {
          return false
        }
      })
    },
    async edit(item) {
      await this.getAllRole()
      this.editForm = Object.assign({}, {
        username: item.username,
        name: item.name,
        id_no: item.id_no,
        mobile: item.mobile,
        roles: item.roles_node,
        password: '',
        id: item.id
      })
      // this.checkedRoles = item.roles_node;
      this.title = '编辑用户 | ' + item.username
      this.text = '密码为空默认不修改密码'
      this.dialogVisible = true
      this.$nextTick(() => {
        this.$refs.editForm.clearValidate()
      })
    },
    search() {
      this.filter.page = 1
      this.getList()
    },
    resetForm() {
      this.filter.page = 1
      this.filter.username = ''
      this.filter.id_no = ''
      this.filter.mobile = ''
      this.getList()
    },
    status(item) {
      const status = item.status === 1 ? 0 : 1
      const msg = item.status === 1 ? '停用成功' : '启用成功'
      statusUser({ id: item.id, status: status }).then(() => {
        this.$message.success(msg)
        this.getList()
      })
    },
    del(item) {
      this.$confirm('此操作将永久删除, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          delUser(item.id).then(() => {
            this.$message.success('删除成功')
            this.getList()
          })
        })
    }
  }
}
</script>
